package android.tusnotas.activities;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.os.Bundle;
import android.tusnotas.beans.AppVersion;
import android.tusnotas.beans.PushStatus;
import android.tusnotas.core.PushSubscriptionAnalyser;
import android.tusnotas.core.PushUnsubscriptionAnalyser;
import android.tusnotas.core.VersionAnalyser;
import android.tusnotas.exception.ProcessingInstancesException;
import android.tusnotas.exception.RemoteReadingException;
import android.tusnotas.model.TusNotasModel;
import android.tusnotas.receivers.VersionReceiver;
import android.tusnotas.services.WebCheckerManager;
import android.tusnotas.util.AlertBuilder;
import android.tusnotas.util.Devel;
import android.tusnotas.util.IdGenerator;
import android.tusnotas.util.Properties;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Toast;

public class CommonActivity extends Activity {

	private Menu menu = null;
	protected WebCheckerManager webCheckerManager = null;
	protected TusNotasModel tusNotasModel = null;

	private KillReceiver mKillReceiver;
	private VersionReceiver versionReceiver;

	private boolean waiting;
	private boolean busy;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mKillReceiver = new KillReceiver();
		IntentFilter intentFilter = new IntentFilter("kill");
		registerReceiver(mKillReceiver,	intentFilter);

		versionReceiver = new VersionReceiver("ShowCourse", this);
		IntentFilter intentVersionFilter = new IntentFilter("version");
		registerReceiver(versionReceiver, intentVersionFilter);

		setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

		tusNotasModel = TusNotasModel.getTusNotasModel(getApplicationContext());
		webCheckerManager = new WebCheckerManager(this);
	}

	@Override
	public boolean onPrepareOptionsMenu(Menu myMenu) {
		menu = myMenu;
		menu.clear();
		MenuInflater inflater = getMenuInflater();
		if (webCheckerManager.isWebCheckerStarted()) {
			inflater.inflate(R.menu.menu_instances_started, menu);
		} else {
			inflater.inflate(R.menu.menu_instances_stopped, menu);
		}
		return Boolean.TRUE;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.configuration:
			Intent welcomeIntent = new Intent(this, Login.class);
			startActivity(welcomeIntent);
			return Boolean.TRUE;

		case R.id.stop:
			Toast t = Toast.makeText(getApplicationContext(),R.string.toast_service_stop, Toast.LENGTH_SHORT);
			t.setGravity(Gravity.CENTER, 0, 0);
			t.show();
			webCheckerManager.stopWebChecker();
			onPrepareOptionsMenu(menu);
			return Boolean.TRUE;

		case R.id.start:
			Toast t1 = Toast.makeText(getApplicationContext(),R.string.toast_service_start, Toast.LENGTH_SHORT);
			t1.setGravity(Gravity.CENTER, 0, 0);
			t1.show();
			webCheckerManager.startWebChecker();
			onPrepareOptionsMenu(menu);
			return Boolean.TRUE;

		case R.id.refresh:
			// refresh(Boolean.TRUE);
			Toast t2 = Toast.makeText(getApplicationContext(),R.string.toast_refresh, Toast.LENGTH_SHORT);
			t2.setGravity(Gravity.CENTER, 0, 0);
			t2.show();
			return Boolean.TRUE;

		case R.id.about:
			AlertBuilder.showAboutInfo(this);
			return Boolean.TRUE;

		case R.id.logout:
			webCheckerManager.stopWebChecker();
			AlertBuilder.logout(this);
			return Boolean.TRUE;

		default:
			return super.onOptionsItemSelected(item);
		}
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		unregisterReceiver(mKillReceiver);
		unregisterReceiver(versionReceiver);
	}


	public void askUserForNewAppVersion(){
		if(!busy){
			_askUserForNewAppVersion();
		}else{
			waiting = true;
		}
	}

	private void _askUserForNewAppVersion(){

		VersionAnalyser va = new VersionAnalyser();
		String appId = getApplicationContext().getPackageName();
		String clientVersion = getActualVersion();
		AppVersion version;
		try {
			version = va.doGetVersion(appId, clientVersion);
			_wantToDownloadNewVersion(version);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void _wantToDownloadNewVersion(AppVersion version){
		String msg;
		if(version.getIsMandatory()){
			msg = getResources().getString(R.string.alert_message_new_version_mandatory);
		}else{
			msg = getResources().getString(R.string.alert_message_new_version_optional);
		}

		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage(msg)
		.setCancelable(false)
		.setPositiveButton(R.string.button_yes, positiveDNV(version))
		.setNegativeButton(R.string.button_no, negativeDNV(version));
		AlertDialog alert = builder.create();
		alert.show();

	}

	private DialogInterface.OnClickListener positiveDNV(AppVersion version){
		return (DialogInterface.OnClickListener)(new PositiveButton(version));
	}

	private class PositiveButton implements DialogInterface.OnClickListener{
		private AppVersion version;
		public PositiveButton(AppVersion version){
			this.version = version;
		}

		public void onClick(DialogInterface dialog, int id) {
			if (version.getLinkLastVersion() == null || version.getLinkLastVersion().equals("")){
				version.setLinkLastVersion("http://www.uade.edu.ar/");
			}
			callBrowser(version.getLinkLastVersion() );   
			if(version.getIsMandatory()){
				logout();
			}
		}

	}

	private void callBrowser(String link){
		Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(link));
		startActivity(browserIntent);
	}

	private DialogInterface.OnClickListener negativeDNV(AppVersion version){
		if(version.getIsMandatory()){
			return (DialogInterface.OnClickListener)(new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int id) {
					logout();
				}
			});
		}else{
			return (DialogInterface.OnClickListener)(new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int id) {
					dialog.cancel();
				}
			});
		}
	}

	private void logout(){
		Intent intent = new Intent("kill");
		getApplicationContext().sendBroadcast(intent);
		// delete old hash
		TusNotasModel.getTusNotasModel(getApplicationContext()).updateProperty(Properties.HASH, "");
		Log.e(getClass().getName(),"Deleted saved hash");
	}
	private String getActualVersion(){
		String app_ver;
		try
		{
			app_ver = this.getPackageManager().getPackageInfo(this.getPackageName(), 0).versionName;
		}
		catch (NameNotFoundException e)
		{
			app_ver = "not_found";
			Log.v(getClass().getSimpleName(), e.getMessage());
		}
		return app_ver;
	}

	final class KillReceiver extends BroadcastReceiver {
		@Override
		public void onReceive(Context context, Intent intent) {
			finish();
		}
	}
//	@Override
//	protected void onPause(){
//		Log.w("", "********** ONPAUSE ACTIVITY");
//	}
//	
//	@Override
//	protected void onResume(){
//		Log.w("", "********** ONRESUME ACTIVITY");
//	}

}
